package com.yjymm.edu.common;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yjymm.edu.model.entity.OrderTable;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import springfox.documentation.service.ApiListing;

import javax.annotation.Resource;
import java.text.CollationElementIterator;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author yjymm
 * @date 2021-01-04 14:19
 */

@Component
@Slf4j
public class RedisUtils {

    private ObjectMapper objectMapper = new ObjectMapper();

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    public Boolean delete(String key) {
        return redisTemplate.delete(key);
    }

    public  Boolean insertList(String key, List<?> value) {
        Long aLong = redisTemplate.opsForList().leftPushAll(key, value);
        redisTemplate.expire(key, (long) (Math.random() * 1000), TimeUnit.SECONDS);
        if (aLong == 1) {
            log.info("插入redis成功");
            return Boolean.TRUE;
        }
        log.info("插入redis失败");
        return Boolean.FALSE;
    }

    public<T> List<T> selectList (String key, Class<T> clazz){
        List<Object> range = redisTemplate.opsForList().range(key, 0, -1);
        if (CollectionUtils.isEmpty(range)){
//            range = (List<Object>)range.get(0);
            return null;
        }
        List<T> tList = new ArrayList();
        range = (List<Object>) range.get(0);
        for (Object o : range) {
            T t = (T)o;
            tList.add(t);
        }
        return tList;
    }

    public Boolean insertMap(String key, Map<String, Object> map) {
        redisTemplate.opsForHash().putAll(key, map);
        return Boolean.TRUE;
    }

    public Boolean insertObject(String key, Object o) throws JsonProcessingException {
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        String s = objectMapper.writeValueAsString(o);
//        System.out.println(s);
        Map map = objectMapper.readValue(s, Map.class);
        redisTemplate.opsForHash().putAll(key, map);
        return Boolean.TRUE;
    }


    public<T> T selectMap2Object (String key, Class<T> clazz) throws JsonProcessingException {
        Map<Object, Object> entries = redisTemplate.opsForHash().entries(key);
        String s = objectMapper.writeValueAsString(entries);
        T t = objectMapper.readValue(s, clazz);
        return t;
    }


}
